import { saveToken, storage } from './storage';
// import React, { Component } from 'react';
import { Alert } from 'react-native';

import { logOut } from '../screens/Home'
import {Loading} from '../tools/Loading'
import {LoadToasting, Toast} from '../tools/Toast'


const qs = require('qs');

const BASE_WEB_URL = 'https://uat.feikongbao.com/';
const BASE_URL = 'https://uat.feikongbao.com/api/';
const DEFAULT_HEADERS = {
  'Content-Type': 'application/json;charset=utf-8',
  'User-Agent': 'FKBSAAS/3 (iPhone; iOS 10.0; Scale/2.00)',
  'fkbLanguage': 'zh',
  'header': "{\"lang\":\"zh\",\"deviceType\":\"x86_64\",\"osVersion\":\"10.0\",\"clientId\":\"373826A1-5A21-4EA5-BADE-331D74D2F72C\",\"version\":\"1.9.3\",\"token\":\"C92C751968A6A313AEFFAC2E3C9CDEEE\",\"appType\":\"iOS\",\"deviceToken\":\"2c2f3a3338e74f4882c86ed7c4cf5cb8\"}",

};


/**
 * 请求 API 接口
 *
 * @param {Object} options
 * @param {string} options.url - 接口地址
 * @param {string} options.method - 请求类型
 * @param {Object} options.headers - 请求头
 * @param {Object} options.params - url 参数
 * @param {Object} options.data - 请求体数据
 */
export default function request({ url, method, headers, params, data, access_token }) {
  let isOk;
  url = BASE_URL + url;
  if (params) {
    url = url + '?' + paramsSerializer(params);
  }
  return new Promise((resolve, reject) => {

    Loading.show();
    fetch(url, {
      method,
      headers: { ...DEFAULT_HEADERS, ...headers, token: access_token },
      body: JSON.stringify(data)
    })
      .then(response => {
        isOk = !!response.ok;
        return response.json();
      })
      .then(responseData => {
        Loading.hidden();
        if (isOk && responseData.statusCode === 200) {
          resolve(responseData);
        } else if(responseData.statusCode === 90001){

          Alert.alert('其他设备登录', '',
          [{ text: "重新登录", onPress:()=>{  

             logOut()
          }}]
        );
        }else {
          // reject(responseData);
          Toast.showError('responseData.msg')
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export function requestWithToken(options) {
  return storage.load({ key: 'accessToken' })
    .then(result => request({ ...options, access_token: result }));
}

export function refreshToken() {

  return storage.load({
    key: 'userInfo'
  }).then(result => {
    return request({
      method: 'POST',
      url: 'token',
      data: {
        mobile: result.mobile,
        password: result.password,
      }
    }).then(data => {
      saveToken(data);
    });
  });
}

/**
 * 请求参数序列化
 *
 * @param {Object} params - 请求参数
 * @returns {string}
 */
function paramsSerializer(params) {
  return qs.stringify(params, { arrayFormat: 'brackets' });
}